#!/usr/bin/env bash
#
# Workstream B: Operational radiance validation with real BUFR data
#

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_section() {
    echo "================================================================================"
    echo "         $1"
    echo "================================================================================"
    echo ""
}

print_section "Radiance BUFR Reader - Operational Data Test"

# CRTM environment (optional)
if [ -f .crtm_config ]; then
    # shellcheck disable=SC1091
    source .crtm_config
    echo -e "${GREEN}✓ CRTM environment loaded${NC}"
else
    echo -e "${YELLOW}⚠ No .crtm_config found, using defaults${NC}"
fi
echo ""

# ecCodes setup
ECCODES_HOME="${ECCODES_HOME:-$HOME/Downloads/FLEXINVERT/code/flexpart/third_party/eccodes-install}"
if [ -d "$ECCODES_HOME" ]; then
    export PATH="$ECCODES_HOME/bin:$PATH"

    base_defs="$ECCODES_HOME/share/eccodes/definitions"
    overlay_defs="$(pwd)/deps/eccodes_overrides"
    definition_paths=()

    if [ -d "$overlay_defs" ]; then
        definition_paths+=("$overlay_defs")
    fi

    current_defs="${ECCODES_DEFINITION_PATH:-}"

    if [ -n "$current_defs" ]; then
        definition_paths+=("$current_defs")
    fi

    if [ -d "$base_defs" ]; then
        if [ -z "$current_defs" ] || [[ ":$current_defs:" != *":$base_defs:"* ]]; then
            definition_paths+=("$base_defs")
        fi
    fi

    if [ ${#definition_paths[@]} -gt 0 ]; then
        joined_path=$(IFS=:; echo "${definition_paths[*]}")
        export ECCODES_DEFINITION_PATH="$joined_path"
    fi

    export ECCODES_SAMPLES_PATH="${ECCODES_SAMPLES_PATH:-$ECCODES_HOME/share/eccodes/samples}"
    echo -e "${GREEN}✓ ecCodes configured from $ECCODES_HOME${NC}"
    if [ -d "$overlay_defs" ]; then
        echo -e "${GREEN}  ↳ Using WMO-13 overlay at $overlay_defs${NC}"
    fi
else
    echo -e "${YELLOW}⚠ ecCodes not found at $ECCODES_HOME${NC}"
fi
echo ""

BUFR_FILE="${1:-/home/linden/code/work/GSI/case_data/2018081212/obs/gdas1.t12z.1bamua.tm00.bufr_d}"
if [ ! -f "$BUFR_FILE" ]; then
    echo "ERROR: BUFR file not found at $BUFR_FILE" >&2
    exit 1
fi

if command -v bufr_count >/dev/null 2>&1; then
    COUNT_OUTPUT=$(bufr_count "$BUFR_FILE" 2>&1)
    echo -e "${BLUE}ecCodes message count:${NC} $COUNT_OUTPUT"
else
    echo -e "${YELLOW}⚠ bufr_count not available on PATH${NC}"
fi

SIZE=$(ls -lh "$BUFR_FILE" | awk '{print $5}')
echo "File        : $BUFR_FILE"
echo "Size        : $SIZE"
echo "Nominal time: 2018-08-12 12:00 UTC"
echo "Instrument  : AMSU-A"
echo ""

echo -e "${BLUE}Running Julia real-data demonstration...${NC}"
GSICORE_RADIANCE_FILE="$BUFR_FILE" \
GSICORE_MAX_OBS="${GSICORE_MAX_OBS:-20000}" \
julia --project=. demos/demo_radiance_real_bufr.jl "$BUFR_FILE"
echo ""

echo -e "${GREEN}✓ Operational BUFR validation complete${NC}"
echo ""
print_section "Status Summary"
echo "✓ CRTM Integration available"
echo "✓ ecCodes installed at $ECCODES_HOME"
echo "✓ Real BUFR read via RadianceBUFRReader"
echo "✓ Summary written to results/radiance_real_summary.json"
echo ""
echo "Next actions:"
echo "  1. Run unit tests: julia --project=. test/test_radiance_bufr_reader.jl"
echo "  2. Run minimization demo: julia --project=. test/test_radiance_minimization.jl"
echo "  3. Compare innovation stats with Fortran GSI (fort.207)"
echo ""
print_section "End"
